from pydive.model import DBSession
from pydive.model.auth import User
from pylons.i18n import ugettext as _
import formencode
from formencode import validators 

class UniqueUsernameValidator(formencode.FancyValidator):
        def _to_python(self, value, state):
            count = DBSession.query(User).filter(User.user_name == value).count()
            if count > 0:
                raise formencode.Invalid(_('That username already exists'),value, state)
            return value
class UniqueEmailValidator(formencode.FancyValidator):
        def _to_python(self, value, state):
            count = DBSession.query(User).filter(User.email_address == value).count()
            if count > 0:
                raise formencode.Invalid(_('That email already exists in our database'),value, state)
            val = formencode.validators.Email().to_python(value, state)
            return val
        
class UserRegisterValidator(formencode.Schema):
        user_name = UniqueUsernameValidator(not_empty=True)
        password = validators.String(not_empty=True)
        password_confirm = validators.String(not_empty=True)
        display_name = validators.String()
        email_address = UniqueEmailValidator(not_empty=True)
        chained_validators = [validators.FieldsMatch('password', 'password_confirm')]